package cn.yh.register.hosp.receiver;

import cn.yh.register.common.constant.MqConst;
import cn.yh.register.common.service.RabbitService;
import cn.yh.register.hosp.service.ScheduleService;
import cn.yh.register.model.hosp.Schedule;
import cn.yh.register.vo.order.OrderMqVo;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 医院服务需要监听订单服务发送到队列的消息
 * 定义mq监听器
 */
@Component
@Slf4j
public class HospitalReceiver {

  @Autowired
  private ScheduleService scheduleService;

  @Autowired
  private RabbitService rabbitService;

  //这个医院服务是干嘛的？  订单服务发送给医院服务一个更新号源的信息
  //医院服务消费信息  更新我们MongoDB中的号源
    @RabbitListener(bindings = @QueueBinding(
                    exchange = @Exchange(name = MqConst.EXCHANGE_DIRECT_ORDER),
                    value = @Queue(name = MqConst.QUEUE_ORDER, durable = "true"),
                    key = MqConst.ROUTING_ORDER))
    public void receive(Message message, Channel channel, OrderMqVo orderMqVo){
      log.info("【医院服务接收更新号源消息】：{}", JSONObject.toJSONString(orderMqVo));
      Schedule schedule;
      // 判断是预约下单的更新号源还是取消预约的更新号源
      if (orderMqVo.getAvailableNumber() != null) {
        // 预约下单的更新号源
        // scheduleId
        String scheduleId = orderMqVo.getScheduleId();
        schedule = scheduleService.getSchedule(scheduleId);
        if (schedule != null) {
          schedule.setReservedNumber(orderMqVo.getReservedNumber());
          schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
        }
      } else {
        // 取消预约的更新号源
        // 医院的排班主键
        String hosScheduleId = orderMqVo.getScheduleId();
        schedule = scheduleService.getByHosScheduleId(hosScheduleId);
        if (schedule == null) {
          return;
        }
        schedule.setAvailableNumber(schedule.getAvailableNumber() + 1);
      }
      // 更新号源
      scheduleService.update(schedule);
      log.info("【医院服务更新号源】：{}", JSONObject.toJSONString(schedule));
      // 发消息给短信服务
      rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, orderMqVo.getMsmVo());
      log.info("【医院服务发送短信通知消息】：{}", JSONObject.toJSONString(orderMqVo.getMsmVo()));
    }
}
